#!/usr/bin/env python
# -*- coding: utf-8 -*-

import tornado
import tornado.web
from utils import log
import json
from config import etc
from controls import data_city_base_mysql
from controls import data_city_map_mysql
from controls import data_img_base_mysql
from controls import data_product_desc_mongo
from controls import data_product_img_mysql
from controls import data_product_desc_title_mysql
from controls import data_card_info_mongo
from controls import data_card_img_mysql
from controls import data_card_collect_mysql
from utils.session_base import ApiGuest
from utils.session_mc import BaseHandler


class ListHandler( BaseHandler ) :

    @ApiGuest
    def post( self ) :
        city_list = data_city_base_mysql.get_city_all()
        if not city_list :
            log.w( 'get city_list failed' )
            res = { 'idx':self.ss_idx, 'ret':1, 'msg':etc.err_500, 'res':{} }
            self.write( json.dumps(res) )
            self.finish()
            return
        city_icon_dict = data_city_map_mysql.get_city_icon_all()
        if not city_icon_dict :
            log.w( 'get city_icon_dict failed' )
            res = { 'idx':self.ss_idx, 'ret':2, 'msg':etc.err_500, 'res':{} }
            self.write( json.dumps(res) )
            self.finish()
            return
        for city in city_list :
            if city_icon_dict.has_key( city["cityid"] ) :
                tmp = city_icon_dict[city["cityid"]]
                if tmp.has_key( city["version"] ) :
                    city["iconfile"] = tmp[city["version"]]
        res = { 'idx':self.ss_idx, 'ret':0, 'msg':'ok', 'res':city_list }
        self.write( json.dumps(res) )
        self.finish()
        return


class GetMapVerHandler( BaseHandler ) :

    @ApiGuest
    def post( self ) :
    #def get( self ) :
        #cityid = self.get_argument( 'cityid', default=2)
        cityid = self.ss_params['cityid']
        version = 0
        # compatible 2.1.0
        try :
            version = int(self.ss_params['version'])
        except Exception as e :
            pass 

        if not cityid :
            log.w( 'cityid fetching error' )
            res = { 'idx':self.ss_idx, 'ret':1, 'msg': etc.err_500, 'res':{} }
            self.write( json.dumps(res) )
            self.finish()
            return

        # get the newest citymap by cityid
        city_map_dict = data_city_map_mysql.get_city_map_by_cityid( int (cityid) )
        if not city_map_dict :
            log.w( 'get city_map failed, cityid:%s' % (cityid) )
            res = { 'idx':self.ss_idx, 'ret':1, 'msg':etc.err_500, 'res':{} }
            self.write( json.dumps(res) )
            self.finish()
            return

        # current city version also is newest
        if city_map_dict['version'] == version:
            res = { 'idx':self.ss_idx, 'ret':0, 'msg':'ok', 'res':{} }
            self.write( json.dumps(res) )
            self.finish()
            return

        if version > 0 and city_map_dict['version'] > version:
            old_city_map_dict = data_city_map_mysql.get_city_map_by_cityid_ver( int (cityid), version )
            # retain changes info
            for key in old_city_map_dict :
                if 'cityid' == key :
                    continue
                if city_map_dict[key] == old_city_map_dict[key] :
                    del city_map_dict[key]
        res = { 'idx':self.ss_idx, 'ret':0, 'msg':'ok', 'res':city_map_dict }
        self.write( json.dumps(res) )
        self.finish()
        return

class ProductHandler( BaseHandler ) :

    @ApiGuest
    def post( self ) :
    #def get( self ) :
        #cityid = self.get_argument( 'cityid', default=1)
        cityid = self.ss_params['cityid']

        if not cityid :
            log.w( 'cityid fetching error' )
            res = { 'idx':self.ss_idx, 'ret':1, 'msg': etc.err_500, 'res':{} }
            self.write( json.dumps(res) )
            self.finish()
            return

        if not data_product_desc_mongo.is_exist( cityid ) :
            res = { 'idx':self.ss_idx, 'ret':0, 'msg': 'no data', 'res':{} }
            self.write( json.dumps(res) )
            self.finish()
            return
        # get all products_list
        products_dict = data_product_desc_mongo.get_city_product( cityid )
        
        product_imgs_raw = data_product_img_mysql.get_product_img_all( cityid )
        if not product_imgs_raw :
            res = { 'idx':self.ss_idx, 'ret':0, 'msg': 'no data', 'res':{} }
            self.write( json.dumps(res) )
            self.finish()
            return
        # get all img
        imgid_dict = data_img_base_mysql.get_img_url_by_imgid_list( product_imgs_raw['imgid_list'] )

        product_imgs = product_imgs_raw['res']
        # get all product img's url
        pid_imgs_dict = {}
        for (pid, imgs) in product_imgs.items() :
            if pid not in pid_imgs_dict :
                pid_imgs_dict[pid] = {}
                pid_imgs_dict[pid]['descimgs'] = []

            # {'imgs': [{'url': 100000005L, 'num': 1L}, {'url': 100000006L, 'num': 0L}, {'url': 100000007L, 'num': 3L}, {'url': 100000008L, 'num': 2L}]}
            for img in imgs['imgs'] :
                if int(img['url']) not in imgid_dict :
                    continue
                imgurl = imgid_dict[ int(img['url']) ]
                if img['num'] == 0:
                    pid_imgs_dict[pid]['icon'] = imgurl
                elif img['num'] == 1:
                    pid_imgs_dict[pid]['mainimg'] = imgurl
                else :
                    pid_imgs_dict[pid]['descimgs'].append(imgurl)
            if 'icon' not in pid_imgs_dict[pid] or 'mainimg' not in pid_imgs_dict[pid] :
                pid_imgs_dict[pid] = None
        
        # get all product titles
        title_list = data_product_desc_title_mysql.get_product_desc_title_all()
        title_dict = {}
        for title_item in title_list :
            title_dict[title_item['descid']] = {'title' : title_item['title'], 'icon': title_item['imgurl'], 'color': title_item['color']}

        # merge data
        #products_list = products_dict['products'.decode(sys.getdefaultencoding())]
        products_list = products_dict['products']
        # get rid of product without icon and main img
        products_list = [ product for product in products_list if product['pid'] in pid_imgs_dict ]
        products_dict['products'] = products_list
        
        for product in products_list :
            cur_pid = product['pid']
            # merge product img url
            product.update(pid_imgs_dict[cur_pid])
            # merge product desc title info
            if 'descs' in product :
                descs_list = product['descs']
                for desc_item in descs_list :
                    desc_item.update(title_dict[desc_item['descid']])

        res = { 'idx':self.ss_idx, 'ret':0, 'msg':'ok', 'res':products_dict }
        self.write( json.dumps(res) )
        self.finish()
        return

'''
获取城市所有卡牌信息，需要传入cityid
'''
class GetCardsHandler( BaseHandler ) :

    @ApiGuest
    def post( self ) :
        cityid = self.ss_params['cityid']
        # get version num from client app
        version = int ( self.ss_params['ver'] )
        if not cityid :
            log.w( 'cityid fetching error' )
            res = { 'idx':self.ss_idx, 'ret':1, 'msg': etc.err_500, 'res':{} }
            self.write( json.dumps(res) )
            self.finish()
            return

        if not data_card_info_mongo.is_exist( cityid ) :
            res = { 'idx':self.ss_idx, 'ret':0, 'msg': 'no data', 'res':{} }
            self.write( json.dumps(res) )
            self.finish()
            return
        # get all cards_list
        cards_dict = data_card_info_mongo.get_city_card( cityid )
        if version == cards_dict['ver'] :
            res = { 'idx':self.ss_idx, 'ret':0, 'msg': 'no newer data', 'res':{"cityid" : cityid, "ver" : version} }
            self.write( json.dumps(res) )
            self.finish()
            return

        card_imgs_raw = data_card_img_mysql.get_card_img_all( cityid )
        if not card_imgs_raw :
            res = { 'idx':self.ss_idx, 'ret':0, 'msg': 'no data', 'res':{} }
            self.write( json.dumps(res) )
            self.finish()
            return
        # get all img
        imgid_dict = data_img_base_mysql.get_img_url_by_imgid_list( card_imgs_raw['imgid_list'] )

        # { cardid : 100000005L, cardid : 100000006L}
        card_imgs = card_imgs_raw['res']
        # get all card img's url
        cardid_imgurl_dict = {}
        for (cardid, imgid) in card_imgs.items() :
            if imgid not in imgid_dict :
                continue
            cardid_imgurl_dict[cardid] = {}
            cardid_imgurl_dict[cardid]['imgid'] = imgid
            cardid_imgurl_dict[cardid]['imgurl'] = imgid_dict[ imgid ]

        # merge data
        #cards_list = cards_dict['cards'.decode(sys.getdefaultencoding())]
        cards_list = cards_dict['cards']
        # get rid of card without imgurl
        cards_list = [ card for card in cards_list if card['cardid'] in cardid_imgurl_dict ]
        cards_dict['cards'] = cards_list
        # get all card's collect count
        coll_count_dict = data_card_collect_mysql.get_collect_count_by_cityid( int(cityid) )
        
        for card in cards_list :
            cur_cardid = card['cardid']
            # merge card img url
            card.update(cardid_imgurl_dict[cur_cardid])

            if cur_cardid in coll_count_dict :
                card['collectcount'] = coll_count_dict[cur_cardid]
            else :
                card['collectcount'] = 0

        res = { 'idx':self.ss_idx, 'ret':0, 'msg':'ok', 'res':cards_dict }
        self.write( json.dumps(res) )
        self.finish()
        return

        
'''
get all sights info by json file
@Deprecated
为向2.1.0兼容，保留
'''
class SightsHandler( BaseHandler ) :

    @ApiGuest
    def post( self ) :
        cityid = self.ss_params['cityid']
        if not cityid :
            log.w( 'cityid fetching error' )
            res = { 'idx':self.ss_idx, 'ret':1, 'msg': etc.err_500, 'res':{} }
            self.write( json.dumps(res) )
            self.finish()
            return

        city_sights_dict = data_city_map_mysql.get_city_map_by_cityid( int (cityid) )
        if not city_sights_dict :
            log.w( 'get city_sights json file failed. cityid=%s' % (cityid) )
            res = { 'idx':self.ss_idx, 'ret':1, 'msg':etc.err_500, 'res':{} }
            self.write( json.dumps(res) )
            self.finish()
            return
        
        res = { 'idx':self.ss_idx, 'ret':0, 'msg':'ok', 'res':city_sights_dict }
        self.write( json.dumps(res) )
        self.finish()
        return

class ApiNotFoundHandler( BaseHandler ) :

    def get( self ) :
        raise tornado.web.HTTPError( 503 )

    @tornado.web.asynchronous
    def post( self ) :
        log.i( '503' )
        res = { 'idx':0, 'ret':9, 'msg':'无此功能', 'res':{} }
        self.write( json.dumps(res) )
        self.finish()


